package co.china.lottery.account.service.impl;

import net.blogjava.frankiegao123.log.slf4j.Log;
import net.blogjava.frankiegao123.log.slf4j.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import co.china.lottery.account.annotation.AccountPrize;
import co.china.lottery.account.dao.PrizeAccountDao;
import co.china.lottery.account.dao.entity.LPrizeAccount;
import co.china.lottery.account.dao.entity.LPrizeAccountHis;
import co.china.lottery.account.service.CreateAccountService;
import co.china.lottery.account.service.code.PrizeIncrementCode;
import co.china.lottery.account.service.code.base.Account;

@Component
@AccountPrize
public class CreatePrizeAccountService implements CreateAccountService {

	private final static Log log = LogFactory.getLog(CreatePrizeAccountService.class);

	@Autowired
	private PrizeAccountDao prizeAccountDao;

	@Override
	public Account getOrCreateAccount(String agentId, boolean isUsing) {

		LPrizeAccount prizeAccount = prizeAccountDao.findAccountByAgentId(agentId);
        if(prizeAccount != null) {
            log.warn("getOrCreateAccount, but prize account already exists, prize account id: {}", prizeAccount.getId());
            return  prizeAccount;
        }
        prizeAccount = LPrizeAccount.getInstance(agentId);
        prizeAccountDao.save(prizeAccount);
        LPrizeAccountHis his = LPrizeAccountHis.getCommit(prizeAccount, 0.0, isUsing ? PrizeIncrementCode.CODE_0001 : PrizeIncrementCode.CODE_0000, 0L,"");
        his.setCommitStatus(LPrizeAccountHis.COMMIT_STATUS_YES);
        prizeAccountDao.save(his);
        prizeAccount.setLastUpdateTime(his.getCreateTime());

        if(isUsing) {
            log.warn("getOrCreateAccount, prize account not exist, CREATE A NEW PRIZE ACCOUNT, agentId: {}, prize account id: {}", agentId, prizeAccount.getId());
        } else {
            log.info("getOrCreateAccount, prize account not exists, create success, prize account id: {}", prizeAccount.getId());
        }
        return prizeAccount;
    }
}